package com.example.sys.wx.controller;

import com.example.core.utils.IdGenerator;
import com.example.core.utils.Result;
import com.example.sys.wx.po.SysWxEventMessage;
import com.example.sys.wx.service.SysWxEventMessageService;
import com.example.sys.wx.service.WechatMpService;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("wx")
public class WechatMpController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private WxMpService wxMpService;

    @Resource
    private WechatMpService wechatMpService;

    @Resource
    private SysWxEventMessageService sysWxEventMessageService;

    @PostMapping("getOpenId")
    public Result getOpenId(@RequestParam String code) {
        try {
            String openId = this.wxMpService.getOAuth2Service().getAccessToken(code).getOpenId();
            return Result.success(openId);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("login")
    public Result login(@RequestParam String code) {
        try {
            String openId = this.wxMpService.getOAuth2Service().getAccessToken(code).getOpenId();
            return Result.success(this.wechatMpService.login(openId));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("getJsapiSignature")
    public Result getJsapiSignature(String url) {
        try {
            WxJsapiSignature jsapiSignature = this.wxMpService.createJsapiSignature(url);
            return Result.success(jsapiSignature);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value = "getQRCode")
    public Result getQRCode() {
        try {
            String id = IdGenerator.generateStringId();
            String target = "/pages/help/index?id=" + id;
            WxMpQrCodeTicket wxMpQrCodeTicket = this.wxMpService.getQrcodeService().qrCodeCreateTmpTicket(target, 60 * 10);
            return Result.success(wxMpQrCodeTicket);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/getQRCodeResult/{ticket}")
    public Result getQRCodeResult(@PathVariable String ticket) {
        try {
            SysWxEventMessage sysWxEventMessage = this.sysWxEventMessageService.getSysWxEventMessageByTicket(ticket);
            return Result.success(sysWxEventMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
}
